import axios from 'axios'
import { getToken } from '@/utils/auth'

const baseUrl = import.meta.env.VITE_APP_BASE_API

const downType = {
  xlsx: 'application/vnd.ms-excel',
  zip: 'application/zip'
}
/**
 *
 * @param {String} url 请求路径
 * @param {*} data 请求参数
 * @param {Object} option 请求配置 {method：请求方式，fileName：下载的文件名，fileType：文件格式}
 */
export function downLoadByUrl(url, data = {}, option) {
  option = {
    method: 'post',
    fileName: undefined,
    fileType: 'xlsx',
    onDownload: e => {},
    ...option
  }
  return new Promise((resolve, reject) => {
    axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
    axios({
      method: option.method,
      url: baseUrl + url, // 请求地址
      data: data, // 参数
      responseType: 'blob', // 表明返回服务器返回的数据类型
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // onDownloadProgress 配置该属性代表允许为下载处理进度事件
      onDownloadProgress: function (progressEvent) {
        //axios封装的原生获取下载进度的事件，该回调参数progressEvent中包含下载文件的总进度以及当前进度
        // console.log("progressEvent", progressEvent);
        // let schedule = {
        //   total: progressEvent.total,
        //   loaded: progressEvent.loaded
        // }
        if (progressEvent.lengthComputable) {
          option.onDownload((progressEvent.loaded / progressEvent.total) * 100)
          //   //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
          //   //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
          //   downLoadProgress.value = progressEvent.loaded / progressEvent.total * 100 //实时获取最新下载进度
        }
      }
    })
      .then(
        response => {
          // console.log(response)
          if (response.data.type == 'application/json') return reject(response)
          resolve(response.data)
          const blob = new Blob([response.data], {
            type: downType[option.fileType]
          })
          // console.log(blob)
          const fileName = option.fileName
            ? option.fileName
            : Date.parse(new Date().toISOString()) + `.${option.fileType}`
          if ((window.navigator as any).msSaveOrOpenBlob) {
            // console.log(2)
            ;(navigator as any).msSaveBlob(blob, fileName)
          } else {
            // console.log(3)
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            //释放内存
            window.URL.revokeObjectURL(link.href)
          }
        },
        err => {
          reject(err)
        }
      )
      .catch(err => {
        reject(err)
      })
  })
}
